<script type="text/javascript">
	var order = <?php echo json_encode($this->order)?>;
	$.fn.serializeObject = function() {
		var o = {};
		var a = $(this).serializeArray();
		for(var i = 0; i < a.length; i++){
			var name = a[i]['name'];
			var value = a[i]['value'];
			if(value == 'on') value = '1';
			if(value == 'off') value = '0';
			o[name] = value;
		}
		return o;
	}
	
	Order = {
		save: function() {
			var data = {};
			data = $.extend(data,$('#customerForm').serializeObject());
			data = $.extend(data,$('#paymentInfo').serializeObject());
			data = $.extend(data,$('#paymentType').serializeObject());
			data.id = order.id;
			data['items'] = [];
			var rooms = $('#roomDg').datagrid('getRows');
			var items = $('#productDg').datagrid('getRows');
			
			for(var i = 0; i < rooms.length; i++){
				rooms[i]['productType'] == 'Room';
				delete rooms[i].editing;
				data['items'].push(rooms[i]);
			}
			for(var i = 0; i < items.length; i++){
				items[i]['productType'] == 'Service';
				delete items[i].editing;
				data['items'].push(items[i]);
			}
			$.ajax({url: '/order/update', type: 'post', data: data, success: function(resp) {
				window.location = '/order';
			}});
		},
		back: function() {
			window.location = '/order';
		},
		print: function() {
			window.location = '/order/print?id=' + order.id
		}
	};
	function addProductToOrder(evt) {
		if(evt.isCat == '0') {
			var items = $('#productDg').datagrid('getRows');
			var orderItem = false;
			var itemIndex = false;
			for(var i = 0; i < items.length; i++) {
				var item = items[i];
				if (item.productId == evt.id) {
					orderItem = item;
					itemIndex = i;
					break;
				}
			}
			if(!orderItem) {
				$('#productDg').datagrid('appendRow',{
					productId: evt.id,
					productName: evt.name,
					productType: 'Service',
					price: evt.price,
					quantity: 1,
					total: evt.price
				});
			} else {
				$('#productDg').datagrid('updateRow',{
					index: itemIndex,
					row: {
						productId: evt.id,
						productName: evt.name,
						price: evt.price,
						quantity: orderItem.quantity + 1,
						total: (orderItem.quantity + 1) * evt.price
					}
				});
			}
			calculateTotal();
		}
	}
	
	function addRoomToOrder() {
		var evt = $('#roomlist').datagrid('getSelected');
		if (evt){
			var items = $('#roomDg').datagrid('getRows');
			var orderItem = false;
			var itemIndex = false;
			for(var i = 0; i < items.length; i++) {
				var item = items[i];
				if (item.productId == evt.id) {
					orderItem = item;
					itemIndex = i;
					break;
				}
			}
			if(!orderItem) {
				$('#roomDg').datagrid('appendRow',{
					productId: evt.id,
					productName: evt.name,
					productType: 'Room',
					price: evt.price,
					quantity: 1,
					total: evt.price,
					startTime: evt.startTime,
					endTime: evt.endTime
				});
			}
			calculateTotal();
		}
	}

	
	function rsearch() {
		var data = $('#fmsearch').serializeObject();
		$('#roomlist').datagrid('load', data);
	}
	
	var gridEditing = {
		gridId : '',
		gridVar: '',
		formatAction: function(value,row,index){
			if (row.editing){
				var s = '<a href="#" onclick="'+this.field+'.saverow(this)">Lưu</a> ';
				var c = '<a href="#" onclick="'+this.field+'.cancelrow(this)">Hủy</a>';
				return s+c;
			} else {
				var e = '<a href="#" onclick="'+this.field+'.editrow(this)">Sửa</a> ';
				var d = '<a href="#" onclick="'+this.field+'.deleterow(this)">Xóa</a>';
				return e+d;
			}
		},
		init: function() {
			var that = this;
			$(function(){
				$(that.gridId).datagrid({
					onBeforeEdit:function(index,row){
						row.editing = true;
						that.updateActions(index,row);
					},
					onAfterEdit:function(index,row){
						row.editing = false;
						that.updateActions(index, row);
					},
					onCancelEdit:function(index,row){
						row.editing = false;
						that.updateActions(index,row);
					}
				});
			});
		},
		updateActions:function(index, row){
			$(this.gridId).datagrid('updateRow',{
				index:index,
				row:{}
			});
			calculateTotal();
		},
		getRowIndex: function (target){
			var tr = $(target).closest('tr.datagrid-row');
			return parseInt(tr.attr('datagrid-row-index'));
		},
		editrow: function (target){
			$(this.gridId).datagrid('beginEdit', this.getRowIndex(target));
			calculateTotal();
		},
		deleterow: function (target){
			var that = this;
			$.messager.confirm('Confirm','Bạn có muốn xóa?',function(r){
				if (r){
					$(that.gridId).datagrid('deleteRow', that.getRowIndex(target));
					calculateTotal();
				}
			});
		},
		saverow: function (target){
			$(this.gridId).datagrid('endEdit', this.getRowIndex(target));
			calculateTotal();
		},
		cancelrow: function (target){
			$(this.gridId).datagrid('cancelEdit', this.getRowIndex(target));
			calculateTotal();
		}
	};
	var roomDg = $.extend({}, gridEditing, {gridId: '#roomDg', gridVar: 'roomDg',
		updateActions: function(index, row) {
			$(this.gridId).datagrid('updateRow',{
				index:index,
				row:{total: calculateRoomTotal(row)}
			});
			calculateTotal();
		},
		formatCalculateTypes: function(val, row, index) {
			switch(val) {
				case 1, '1': return 'Theo ngày';
				case 2, '2': return 'Theo giờ';
				case 3, '3': return 'Theo ngày và giờ';
				return 'Theo ngày';
			}
		}
		
	});
	roomDg.init();
	var productDg = $.extend({}, gridEditing, {gridId: '#productDg', gridVar: 'productDg',
		updateActions: function(index, row) {
			$(this.gridId).datagrid('updateRow',{
				index:index,
				row:{total: (row.price * row.quantity)}
			});
			calculateTotal();
		}
		
	});
	productDg.init();
	function calculateDuration(startTime, endTime) {
		var d1 = new Date(startTime);
		var d2 = new Date(endTime);
		var m = d2.getTime() - d1.getTime();
		var dDuration = (1000 * 60 * 60 * 24);
		var ds = Math.round(m / dDuration);
		m = m - ds * dDuration;
		var hs = Math.round(m / (1000 * 60 * 60));
		return {days: ds, hours: hs};
	}
	var pricing = <?php echo $this->pricing?>; // php
	function calculateRoomTotal(row){
		var duration = calculateDuration(row.startTime, row.endTime);
		if(!row.calculateType || parseInt(row.calculateType) == 1) {
			return pricing[row.productId].ngay1 * duration.days;
		} else if (parseInt(row.calculateType) == 2) {
			return pricing[row.productId].gio1 * duration.hours;
		} else {
			return parseFloat(pricing[row.productId].gio1) * duration.hours + parseFloat(pricing[row.productId].ngay1) * duration.days;
		}
	}
	function calculateTotal() {
		var rooms = $('#roomDg').datagrid('getRows');
		var items = $('#productDg').datagrid('getRows');
		var total = 0;
		for(var i = 0; i < rooms.length; i++){
			total += parseFloat(rooms[i].total);
		}
		for(var i = 0; i < items.length; i++){
			total += parseFloat(items[i].total);
		}
		var prepaid = parseFloat($('#prepaid').val());
		var fee = parseFloat($('#fee').val());
		var promotion = parseFloat($('#promotion').val());
		if(prepaid) {
			if(prepaid < 100) {
				total = total * (100 - prepaid) / 100;
			} else {
				total -= prepaid;
			}
		}
		if(fee) {
			if(fee < 100) {
				total = total * (100 + prepaid) / 100;
			} else {
				total += fee;
			}
			
		}
		if(promotion) {
			if(promotion < 100) {
				total = total * (100 - promotion) / 100;
			} else {
				total = total - promotion;
			}
		}
		
		$('#totalSpan').html(formatPrice(total));
		$('#total').val(total);
	}
	
	$(function(){
		$('#customerForm').form('load', order);
		$('#paymentInfo').form('load', order);
		$('#paymentType').form('load', order);
		var rooms = [];
		var products = [];
		for(var i = 0; i < order.items.length; i++) {
			if(order.items[i].productType == 'Room')
				rooms.push(order.items[i]);
			else if(order.items[i].productType == 'Service')
				products.push(order.items[i]);
		}
		$('#roomDg').datagrid('loadData', rooms);
		$('#productDg').datagrid('loadData', products);
		calculateTotal();
	});
</script>
<form id="customerForm" method="post" enctype="multipart/form-data">
	<table border="0" width="auto" cellspacing="0" cellpadding="4"
		class="tblForm">
		<tr>
			<td width="100px;">
				<div>Tên khách hàng:</div>
			</td>
			<td class="2Col"><input id="customerName" name="customerName"
				data-options="required:true" class="easyui-validatebox"
				style="width: 150px"></td>
			<td>
				<div>Công ty</div>
			</td>
			<td><input id="customerCompany" name="customerCompany"
				class="easyui-validatebox" style="width: 150px" type="text" /></td>
		</tr>
		<tr>
			<td>
				<div>CMND / Hộ chiếu:</div>
			</td>
			<td class="2Col"><input id="customerPassport" name="customerPassport"
				data-options="required:true" class="easyui-text"
				style="width: 150px"></td>
			<td>
				<div>Điện thoại công ty</div>
			</td>
			<td><input id="customerCompanyPhone" name="customerCompanyPhone" class="easyui-validatebox"
				style="width: 150px" type="text" /></td>
		</tr>
		<tr>
			<td>
				<div>Điện thoại:</div>
			</td>
			<td class="2Col"><input id="customerPhone" name="customerPhone" class="easyui-text"
				style="width: 150px"></td>
			<td>
				<div>Fax công ty:</div>
			</td>
			<td class="2Col"><input id="customerCompanyFax" name="customerCompanyFax"
				class="easyui-validatebox"
				style="width: 150px"></td>
		</tr>
		<tr>
			<td>
				<div>Địa chỉ:</div>
			</td>
			<td class="2Col"><input id="customerAddress" name="customerAddress"
				class="easyui-text" style="width: 150px;"></td>
			<td>
				<div>Địa chỉ công ty</div>
			</td>
			<td class="2Col"><input id="customerCompanyAddress" name="customerCompanyAddress"
				class="easyui-text" style="width: 150px;"></td>
			
		</tr>
	</table>
</form>
<table>
	<tr style="height: 300px;">
		<td style="width: 360px">
			<form id="fmsearch" method="post" enctype="multipart/form-data">
				<table border="0" width="90%" cellspacing="0" style="padding-top: 3px;"
					cellpadding="1" class="tblForm">
					<tr>
						<td>
							<span>Từ:</span>
						</td>
						<td>
							<input id="startTime" name="startTime" class="easyui-datetimebox" style="border: 1px solid #ccc">
						</td>
					</tr>
					<tr>
						<td><span>Đến:</span></td>
						<td>
							<input id="endTime" name="endTime" class="easyui-datetimebox" >
						</td>
						<td><a href="#" class="easyui-linkbutton" iconCls="icon-search"
							plain="true" onclick="rsearch()">Tìm kiếm</a></td>
					</tr>
				</table>
			</form>
			<table id="roomlist" class="easyui-datagrid" title="Danh sách phòng" style="width: 100%;"
				pagination="true" idField="id" rownumbers="true" url="/room/search"
				fitColumns="true" singleSelect="true" nowrap="true" 
				data-options="border:false,fit:true,onDblClickRow:addRoomToOrder">
				<thead>
					<tr>
						<th field="name" width="100">Tên</th>
						<th field="price" width="60" align="right" formatter="formatPrice">Giá</th>
						<th field="statusName" width="90" align="right">Trạng thái</th>
						<th field="id" data-options="hidden:true">Id</th>
					</tr>
				</thead>
			</table>
		</td>
		<td style="width: 750px;">
			<table id="roomDg" title="Phòng đã đặt" style="width: 100%;"
				pagination="true" idField="id" rownumbers="true"
				fitColumns="true" singleSelect="true" nowrap="true" 
				data-options="border:false,fit:true">
				<thead>
					<tr>
						<th field="productName" width="120" sortable="true">Dịch vụ</th>
						<th field="price" width="150" formatter="formatPrice">Giá</th>
						<th field="startTime" width="150" class="easyui-datetimebox" editor="text">Ngày đến</th>
						<th field="endTime" width="150" class="easyui-datetimebox" editor="text">Ngày đi</th>
						<th field="calculateType" width="150" editor="{  
                            type:'combobox',  
                            options:{  
                                valueField:'value',  
                                textField:'label',  
                                url:'/order/calculatetypes',  
                                required:true  
                            }  
                        }" formatter="roomDg.formatCalculateTypes">Tính theo</th>
						<th field="quantity" width="70" editor="text">Số người</th>
						<th field="total" width="120" formatter="formatPrice">Tổng cộng</th>
						<th field="id" data-options="hidden:true">Id</th>
						<th field="productId" data-options="hidden:true">Product Id</th>
						<th field="productType" data-options="hidden:true">Product Type</th>
						<th field="roomDg" width="80" align="center" formatter="roomDg.formatAction">Action</th>
					</tr>
				</thead>
			</table>
		</td>
	</tr>
</table>
<table>
	<tr>
		<td style="width: 360px">
			<table id="productlist" title="Danh mục dịch vụ" class="easyui-treegrid" style="width:360px;height:300px"
					url="/tree/children?id=7"
					rownumbers="true" data-options="onDblClickRow:addProductToOrder"
					idField="id" treeField="name">
				<thead>
					<tr>
						<th field="name" width="150">Tên</th>
						<th field="price" width="80" align="right" formatter="formatPrice">Giá</th>
						<th field="quantity" width="80" align="right">Số lượng</th>
					</tr>
				</thead>
			</table>
		</td>
		<td style="width: 750px;">
			<table id="productDg" title="Dịch vụ đã đặt" style="width: 100%;"
				pagination="true" idField="id" rownumbers="true"
				fitColumns="true" singleSelect="true" nowrap="true" 
				data-options="border:false,fit:true">
				<thead>
					<tr>
						<th field="productName" width="120" sortable="true">Dịch vụ</th>
						<th field="price" width="150" formatter="formatPrice">Giá</th>
						<th field="quantity" editor="{type:'validatebox',options:{required:true}}" width="70">Số lượng</th>
						<th field="total" width="120" formatter="formatPrice">Tổng cộng</th>
						<th field="id" data-options="hidden:true">Id</th>
						<th field="productId" data-options="hidden:true">Product Id</th>
						<th field="productType" data-options="hidden:true">Product Type</th>
						<th field="productDg" width="80" align="center" formatter="productDg.formatAction">Action</th>
					</tr>
				</thead>
			</table>
		</td>
	</tr>
</table>
<form id="paymentInfo">
<table>
	<tr>
		<td>Trả trước</td>
		<td><input id="prepaid" name="prepaid" class="easyui-text"
				style="width: 150px" onkeyup="calculateTotal();"/></td>
		<td>Khoản khác</td>
		<td><input id="fee" name="fee" class="easyui-text"
				style="width: 150px" onkeyup="calculateTotal();"/></td>
		<td>Khuyến mại</td>
		<td><input id="promotion" name="promotion" class="easyui-text"
				style="width: 150px" onkeyup="calculateTotal();" /></td>
		<td>Tổng cộng</td>
		<td><span id="totalSpan"></span><input id="total" name="total" type="hidden" style="width: 150px" /></td>
	</tr>
</table>
<form id="paymentType">
<table>
	<tr>
		<td style="width: 30px;"><input id="payment" name="payment" type="checkbox" value="1" /></td>
		<td colspan="5">Thanh toán</td>
	</tr>
	<tr>
		<td><input id="checkmo" name="checkmo" type="checkbox" value="1" /></td>
		<td>Trực tiếp</td>
		<td><input id="card" name="card" type="checkbox" value="1"/></td>
		<td>Qua thẻ</td>
		<td><input id="debit" name="debit" type="checkbox" value="1"/></td>
		<td>Nợ</td>
	</tr>
	<tr>
		<td colspan="6">
			<a href="#" class="easyui-linkbutton"
		iconCls="icon-save" onclick="Order.save();">Lưu</a>
			<a href="#" class="easyui-linkbutton"
		iconCls="icon-print" onclick="Order.print();">In hóa đơn</a>
			<a href="#" class="easyui-linkbutton"
		iconCls="icon-back" onclick="Order.back();">Trở lại</a>
		</td>
	</tr>
</table>